import { useMemberStore } from '@/stores'
const memberStore = useMemberStore()
// 请求头
const baseUrl = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
const httpInterceptor = {
  invoke(options: UniApp.RequestOptions) {
    if (!options.url.startsWith('http')) {
      options.url = baseUrl + options.url
      // 设置请求头
      options.header = {
        ...options.header,
        'source-client': 'miniapp',
      }
      // 设置超时时间
      options.timeout = 10000
      const token = memberStore.profile?.token
      if (token) {
        options.header.Authorization = token
      }
    }
  },
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

// 接口返回数据类型
interface Data<T> {
  code: string
  msg: string
  result: T
}
// 封装请求方法
export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      // 响应成功
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          memberStore.clearProfile()
          uni.navigateTo({ url: '/pages/login/login' })
          reject(res)
        } else {
          uni.showToast({ title: (res.data as Data<T>).msg || '请求失败', icon: 'none' })
          reject(res)
        }
      },
      // 响应失败
      fail: (err) => {
        uni.showToast({ title: '网络错误', icon: 'none' })
        reject(err)
      },
    })
  })
}
